/* eslint-disable import/no-anonymous-default-export */
/**
 * @description 
 * @author cq
 * @Date 2021-04-07 15:32:34
 * @LastEditTime 2021-04-07 18:00:50
 * @LastEditors cq
 */
export default (...middle)=>{
  return createStore => reducer=>{

    //先拿到我们原来的store
    const store = createStore(reducer);
    let dispatch = store.dispatch;  //加强版的dispatch默认值取之前的dispatch

    // todo 修改一份支持异步请求的dispatch

    const midApi = {
      getState: store.getState,
      // 写成函数是因为多个中间件形成的作用域互不影响
      dispatch: action => dispatch(action)
    };

    // 先把中间件执行一遍 把所需要的参数 getState dispatch 传进去
    const middlewareChain = middle.map(middleware => middleware(midApi));

    // console.log(middle[1],222)
    // console.log(middlewareChain[1](store.dispatch)(store.dispatch), "middlewareChain")
    // 重新赋值一个函数
    // 每次执行dispatch都要把所有的dispatch都执行一遍
    dispatch = compose(...middlewareChain)(store.dispatch);

    return {
      ...store,
      dispatch
    }
  }
}


// 聚合执行
function compose(...funcs) {
  if (funcs.length === 0) {
    return arg => arg;
  }
  if (funcs.length === 1) {
    return funcs[0];
  }
  return funcs.reduce((a, b) => (...args) => a(b(...args)));
}